﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.BizFacade.Services.Contents;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.SystemFacade.Globalization;

namespace Fuse8.ContentManagementFramework.Administration.Models.MetaFields
{
    [MetaFieldValuesProvider]
    public class LinkedContentMetaFieldValuesProvider : IMetaFieldValuesProvider
    {
        public string Name
        {
            get { return "Linked Content"; }
        }

        public string AdministrationViewName
        {
            get { return "ContentTypePicker"; }
        }

        public bool CanAddItem
        {
            get
            {
                return true;
            }
        }

        public IEnumerable<CmsKeyValueItem> GetDataSource(string settings)
        {
            
            return
                GenericContentService.GetAll(Convert.ToInt32(settings)).ToList().Select(
                        p => new CmsKeyValueItem() {Key = p["PublicContentId"].ToString(), Value = p["ContentTitle"].ToString()});
        }

        public SelectListItem AddNewItem(string text, string settings)
        {
            int contentType = Convert.ToInt32(settings);
            var item = new CmsContent()
                           {
                               ContentTitle = text,
                               ContentTypeId = contentType
                           };
            new CmsContentService().Add(item);

            return new SelectListItem() {Text = item.ContentTitle, Value = item.Id.ToString()};
        }

        public string GetSettings(ControllerContext modelState)
        {
            return modelState.HttpContext.Request.Form["ContentTypeId"];
        }

        public void SetSettings(ViewDataDictionary viewData, string settings)
        {
            viewData["ContentTypes"] = new CmsContentTypeService().FindAll().ToList();
            int id;
            int.TryParse(settings, out id);
            viewData["ContentTypeId"] = id > 0 ? id : new int?();
        }
    }
}